package com.bingkaimedia.merchantbeta.app;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bingkaimedia.merchantbeta.R;
import com.bingkaimedia.merchantbeta.libs.AlertDialogManager;
import com.bingkaimedia.merchantbeta.libs.JSONfunctions;
import com.bingkaimedia.merchantbeta.libs.LazyAdapter;
import com.bingkaimedia.merchantbeta.libs.SessionManager;
import com.bingkaimedia.merchantbeta.libs_image.ImageLoader;
import com.bingkaimedia.merchantbeta.libs_slidemenu.BaseActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

@SuppressLint("NewApi")
public class List_Data_Detail extends BaseActivity {
	
	int current_page = 0;
	
	
	
	// XML node keys 
	//static final String KEY_SONG = "song"; // parent node
	static final String KEY_VOUCHER_ID = "voucher_id";
	static final String KEY_VOUCHER_NAME = "voucher_name";
	static final String KEY_VOUCHER_TOTAL = "voucher_total";
	static final String KEY_VOUCHER_TERSEDIA = "voucher_tersedia";
	static final String KEY_VOUCHER_DETAIL = "voucher_detail";
	static final String KEY_VOUCHER_DATE = "voucher_date";
	static final String KEY_VOUCHER_DESCRIPTION = "voucher_description";
	static final String KEY_MERCHANT_ID = "merchant_id";
	static final String KEY_MERCHANT_NAME = "merchant_name";
	static final String KEY_CHANNEL_ID = "channel_id";
	static final String KEY_CHANNEL_NAME = "channel_name";
	static final String KEY_MERCHANT_PHOTO = "merchant_photo";
	static final String KEY_CATEGORY_NAME = "merchant_category";

	private String xml_voucher_id;
	private String xml_voucher_name;
	//private String xml_voucher_total;
	//private String xml_voucher_tersedia;
	private String xml_voucher_description;
	private String xml_voucher_detail;
	private String xml_voucher_date;
	private String xml_merchant_id;
	private String xml_merchant_name;
	private String xml_channel_id;
	private String xml_channel_name;
	private String xml_merchant_photo;
	private String xml_category_name;
	
	
	private String session_userid;
	private String session_username;
	private String session_password;
	private String session_email;
	private String session_country;
	private String session_country_name;
	private String session_city;
	private String session_city_name;
	private String session_checked;
	private String session_channel;
	private String session_category;
	private String session_category_name;
    
    
	// Alert Dialog Manager
		AlertDialogManager alert = new AlertDialogManager();
    public ImageLoader imageLoader; 
    
    private String idtransaksi;
    
 // Session Manager Class
 	SessionManager session;
 	
 	LazyAdapter adapter;
 	ArrayList<HashMap<String, String>> menuItems;
 	ProgressDialog pDialog;
 	HashMap<String, String> map = new HashMap<String, String>();
 	
 	ArrayList<HashMap<String, String>> diskonba_list = new ArrayList<HashMap<String, String>>();
 	
 	//ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
 	
 	//slide menu
 	private LinearLayout slidingPanel;
 	private boolean isExpanded;
 	private DisplayMetrics metrics;
 	private RelativeLayout headerPanel;
 	private int panelWidth;
 	private int panelWidth1;

 	private String id_;
 	ArrayList nameValuePairs; 
	InputStream is = null;
	StringBuilder sb=null;
	ImageLoader imgLoader;
	
 	private ImageView menuViewButton,menuRightButton;

 	FrameLayout.LayoutParams menuPanelParameters;
 	FrameLayout.LayoutParams slidingPanelParameters;
 	LinearLayout.LayoutParams headerPanelParameters;
 	LinearLayout.LayoutParams listViewParameters;
 	

	private int count;
	private String json;
	private String result;
	private JSONObject jsonobject;
	public String code;
	public String msg;
	
	private Button send;
	private Button cancel;
	
	private SlidingMenu sm;
	 
	public List_Data_Detail() {
		super(R.string.baru); 
	}


	@Override
	public void onBackPressed() { 
		List_Data_Detail.this.finish();
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_data_detail);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        
        
       
     	fungsi_menu();	
     	 

		nameValuePairs = new ArrayList();
		
		imgLoader = new ImageLoader(getApplicationContext());
		
		session = new SessionManager(getApplicationContext());
	    
	    HashMap<String, String> user = session.getUserDetails();
	     
	    // name
	    session_userid = user.get(SessionManager.id_users);
	    session_username = user.get(SessionManager.username);
	    session_password = user.get(SessionManager.password);
	    session_email = user.get(SessionManager.email);
	    session_country = user.get(SessionManager.country);
	    session_country_name = user.get(SessionManager.country_name);
	    session_city = user.get(SessionManager.city);
	    session_city_name = user.get(SessionManager.city_name);
	    session_checked = user.get(SessionManager.checked);
	    session_channel = user.get(SessionManager.channel);
	    session_category = user.get(SessionManager.category);
	    session_category_name = user.get(SessionManager.category_name);
	    
	    //System.out.println("session");
	    //System.out.println(session_userid);
	    //System.out.println(session_username);
	    //System.out.println(session_password);
	    //System.out.println(session_email);
	    //System.out.println(session_country);
	    //System.out.println(session_country_name);
	    //System.out.println(session_city);
	    //System.out.println(session_city_name);
	    //System.out.println(session_checked);
	    //System.out.println(session_channel);
	    //System.out.println(session_category);
	    //System.out.println(session_category_name);
	     
	     
	    TextView channel = (TextView)findViewById(R.id.txt_channel_name);
	    channel.setText(session_channel);
	    
	    //TextView city_category = (TextView)findViewById(R.id.city_category);
	    //city_category.setVisibility(0);
	    if (session_category == "")
	    {
	    	//city_category.setText(session_city_name + " - " + "[ ALL ]");
	    }
	    else
	    {
	    	//city_category.setText(session_city_name + " - " + "[ " + session_category_name +" ]");
	    }

	 // getting intent data
        Intent in = getIntent();
         
        // Get XML values from previous intent
        id_ = in.getStringExtra(KEY_VOUCHER_ID);
        //String title_ = in.getStringExtra(KEY_MERCHANT_NAME);
        //String artist_ = in.getStringExtra(KEY_VOUCHER_NAME);
        //String duration_ = in.getStringExtra(KEY_VOUCHER_TOTAL);
        //String thumb_url_ = in.getStringExtra(KEY_MERCHANT_PHOTO);
        
        new loadListView().execute();
        
         
		send=(Button)findViewById(R.id.button1); 
		
		send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{ 
				
	    	    SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd.HHmmss");
	    		String format = s.format(new java.util.Date());
	    		
	    	    idtransaksi = xml_voucher_id + "." + xml_merchant_id + "." + session_userid + "." + format; 
	    	    //System.out.println("id transaksi : "+ idtransaksi);
	    	    
	    	    
	    	    AlertDialog.Builder builder=new AlertDialog.Builder(List_Data_Detail.this);
				builder.setTitle("Take voucher")
				.setMessage("Are you sure want to take voucher ?")
				.setPositiveButton("Yes",new DialogInterface.OnClickListener()
				{
						public void onClick(DialogInterface dialog,int id)
						{
							new Check().execute();
							
							//Intent intent=new Intent(getApplicationContext(),Home.class);
		    				//startActivity(intent);
		    				//List_Data_Detail.this.finish();
						}
				  }) 
				  .setNegativeButton("No",new DialogInterface.OnClickListener()
				  {
						public void onClick(DialogInterface dialog,int id) 
						{
							  
						}
				  })
				  .show();	
			}
		});
    		 
    }
	
	
	
	public void fungsi_menu(){
		
		setSlidingActionBarEnabled(true);
		 
        sm = getSlidingMenu();
		 
		LinearLayout header_vertical_divider_1 = (LinearLayout) findViewById(R.id.header_vertical_divider_1);
		LinearLayout header_vertical_divider_2 = (LinearLayout) findViewById(R.id.header_vertical_divider_2);
		ImageView diskonion_iconmenu = (ImageView) findViewById(R.id.diskonion_iconmenu);
		ImageView diskonion_iconhome = (ImageView) findViewById(R.id.diskonion_iconhome);
		ImageView diskonion_iconsearch = (ImageView) findViewById(R.id.diskonion_iconsearch);
		ImageView diskonion_iconcategory = (ImageView) findViewById(R.id.diskonion_iconcategory);
		
		 
		
		diskonion_iconmenu.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showMenu(); 
			}
		}); 
		
		diskonion_iconhome.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconsearch.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				//sm.showSecondaryMenu();
 				Intent intent=new Intent(getApplicationContext(),Home.class);
 				startActivity(intent);
			}
		});
		
		diskonion_iconcategory.setOnClickListener(new OnClickListener() { 
	 			public void onClick(View v)  {
				sm.showSecondaryMenu(); 
			}
		});
 		
	}
	
	
	@SuppressLint("NewApi")
	private class loadListView extends AsyncTask<Void, Void, Void>  {

		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog = new ProgressDialog(List_Data_Detail.this);
			pDialog.setMessage("Retrieve Data, Please wait...");
			pDialog.setCancelable(true);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
			 
			Global.URL = Global.link_list_data_detail + id_;
			code="99";
			msg="Not connected to server";
			
    		
			try{ 
				json=JSONfunctions.getStringContent(Global.URL);
				jsonobject=new JSONObject(json); 
				code=jsonobject.getString("code");
				msg=jsonobject.getString("msg");
				 
			}
			catch (Exception e) 
			{
				e.printStackTrace();
				System.out.println("catch code msg");
				System.out.println(e);
				//pDialog.dismiss();
				//Toast.makeText(getApplicationContext(), "Something wrong in your connection", Toast.LENGTH_LONG).show();
			
			}
			
			System.out.println("code "+code);
			if(code.equalsIgnoreCase("99")){
				try{ 
					System.out.println(Global.URL);
					//json=JSONfunctions.getStringContent2(Global.URL);
					System.out.println(json); 
					 
				}
				catch (Exception e) 
				{
					e.printStackTrace();
					System.out.println("catch 1");
					System.out.println(e);

					//pDialog.dismiss();
					//Toast.makeText(getApplicationContext(), "Something wrong in your connection (1)", Toast.LENGTH_LONG).show();
				
				}
			}
			return null;
    		 
				 
		}
		
		
		protected void onPostExecute(Void unused) {
			result = json;
					
			if(code.equalsIgnoreCase("0")){
				
				Toast.makeText(getBaseContext(), msg, Toast.LENGTH_LONG).show();
			}
			else{
				try{
		      	JSONArray jArray = new JSONArray(result);
		      	JSONObject json_data=null;
	
		      	//System.out.println("array length");
		      	//System.out.println(jArray.length());
		      	
		      	
		      	for(int i=0;i<jArray.length();i++){
						json_data = jArray.getJSONObject(i); 
						
						  
						xml_channel_id = json_data.getString(KEY_CHANNEL_ID);
						xml_channel_name = json_data.getString(KEY_CHANNEL_NAME);
						xml_voucher_id = json_data.getString(KEY_VOUCHER_ID);
						xml_voucher_name = json_data.getString(KEY_VOUCHER_NAME);
						//xml_voucher_total = json_data.getString(KEY_VOUCHER_TOTAL);
						//xml_voucher_tersedia = json_data.getString(KEY_VOUCHER_TERSEDIA);
						xml_voucher_description = json_data.getString(KEY_VOUCHER_DESCRIPTION);
						xml_voucher_detail = json_data.getString(KEY_VOUCHER_DETAIL);
						xml_voucher_date = json_data.getString(KEY_VOUCHER_DATE);
						xml_merchant_id = json_data.getString(KEY_MERCHANT_ID);
						xml_merchant_name = json_data.getString(KEY_MERCHANT_NAME);
						xml_merchant_photo = json_data.getString(KEY_MERCHANT_PHOTO);
						xml_category_name = json_data.getString(KEY_CATEGORY_NAME);
						
	
						//System.out.println(xml_voucher_id);
						//System.out.println(xml_voucher_name);
						////System.out.println("Total - " + xml_voucher_total);
						////System.out.println("Tersedia - " + xml_voucher_tersedia);
						//System.out.println(xml_voucher_description);
						//System.out.println(xml_voucher_detail);
						//System.out.println(xml_merchant_id);
						//System.out.println(xml_merchant_name);
						//System.out.println(Global.path + xml_merchant_photo);
			 	 
			      	}
			      	
				}catch(JSONException e1){ 
					System.out.println("catch 2");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (2)", Toast.LENGTH_LONG).show();
				}catch (ParseException e1){ 
					System.out.println("catch 3");
					System.out.println(e1);
					Toast.makeText(getBaseContext(), "Something wrong in your connection (3)", Toast.LENGTH_LONG).show();	
				} 
			}	
		 
			
			TextView txt_channel_id = (TextView)findViewById(R.id.txt_channel_id);
	        TextView txt_channel_name = (TextView)findViewById(R.id.txt_channel_name); // title
			TextView txt_voucher_id = (TextView)findViewById(R.id.txt_voucher_id);
	        TextView txt_voucher_name = (TextView)findViewById(R.id.txt_voucher_name); // title
	        TextView txt_voucher_detail = (TextView)findViewById(R.id.txt_voucher_detail); // title
	        TextView txt_voucher_date = (TextView)findViewById(R.id.txt_voucher_date); // title
	        TextView txt_voucher_description = (TextView)findViewById(R.id.txt_voucher_description); // title
	        TextView txt_merchant_name = (TextView)findViewById(R.id.txt_merchant_name); // artist name
	        //TextView txt_voucher_total = (TextView)findViewById(R.id.txt_voucher_total); // duration
	        //TextView txt_voucher_tersedia = (TextView)findViewById(R.id.txt_voucher_tersedia); // duration
	        ImageView txt_merchant_photo =(ImageView)findViewById(R.id.txt_merchant_photo); // thumb image
	        TextView txt_category_name =(TextView)findViewById(R.id.txt_category); // thumb image
	        
        	txt_voucher_id.setVisibility(View.GONE);
        	
        	//int a=Integer.parseInt(xml_voucher_tersedia);
        	////System.out.println("a"+a);
        	//if(a  <= 0)
        	//{
        	//	send.setEnabled(false);
        	//}

        	txt_channel_id.setText(xml_channel_id);
	        txt_channel_name.setText(xml_channel_name);
	        txt_voucher_id.setText(xml_voucher_id);
	        txt_voucher_name.setText(xml_voucher_name);
	        txt_voucher_detail.setText(xml_voucher_detail);
	        txt_voucher_date.setText(xml_voucher_date);
	        txt_voucher_description.setText(xml_voucher_description);
	        txt_merchant_name.setText(xml_merchant_name);
	        txt_category_name.setText(xml_category_name);
	        //txt_voucher_total.setText("Total voucher  : " + xml_voucher_total);
	        //txt_voucher_tersedia.setText("Nilai Point : " + xml_voucher_tersedia);
	        imgLoader.DisplayImage(Global.path + xml_merchant_photo, txt_merchant_photo);
	        
		        
			pDialog.dismiss();
		}
	}
	
	@SuppressLint("NewApi")
	class Check extends AsyncTask {

		private String json;
		private JSONObject jsonobject;
		private String code;
		private String msg;
		public String url2;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(List_Data_Detail.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(true);
			pDialog.show();
			url2 = Global.link_insert +
					"transaction_id="+idtransaksi+"&"+ 
					"voucher_id="+xml_voucher_id+"&"+
					"users_id="+session_userid+"&"+
					"channel_id="+xml_channel_id+"&"+
					"status="+"0";
			
			 
			url2 = url2.replace("+", "%20");
			url2 = url2.replace(" ", "%20"); 
			System.out.println(url2);

		}

		@Override
		protected Object doInBackground(Object... params) {
			code="99";
			msg="Not connected to server";
			
			try {
				json = JSONfunctions.getStringContent(url2);
				jsonobject = new JSONObject(json);
				code = jsonobject.getString("code");
				//code = "1";
				msg = jsonobject.getString("msg");
				//Toast.makeText(getApplicationContext(), "Mohon Tunggu",
				//		30000).show();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			
			if (pDialog.isShowing())
				pDialog.dismiss(); 
			
			if (code.equalsIgnoreCase("1")) { 
 
	             
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(List_Data_Detail.this); 
	            alertDialog.setTitle("Information"); 
	            alertDialog.setMessage(msg); 
	            alertDialog.setIcon(R.drawable.image_success); 
	            alertDialog.setPositiveButton("OK",
	                    new DialogInterface.OnClickListener() {
	                        public void onClick(DialogInterface dialog,int which) {
	                            // Write your code here to execute after dialog
	                        	Intent i = new Intent(getApplicationContext(), My_Voucher.class);
	                            startActivity(i); 
	                            finish();
	                        }
	                    });
	            

	            // Showing Alert Message
	            alertDialog.show();
	            
				
			} else {
				alert.showAlertDialog(List_Data_Detail.this, "Information", msg, false);
			}
		}
		
	 
	}
	
	
}
